package fileLoader;


import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 
 * class which handles contact with database(Adding or removing tags)
 *
 */
public class DBTagsMgr {

	
	private static Socket socket=null;//socket for updating the GUI
	private static PrintWriter out=null;
	
	/**
	 * 
	 * @param file_path
	 * @param labels
	 * adds file_path with each label to the data base
	 */
	public static void addTags(String file_path, String[] labels)
	{
		int i;
		boolean flag=false;
		for(i=0;i<labels.length;i++)
		{
			//creating new Tag for the file for each label
			Tag tag=new Tag();
			tag.setTag(labels[i]);
			tag.setFilePath(file_path);


			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 

			Session session = sessionFactory.openSession();
			TagsManager manager = new TagsManager(session);

			//getting all tag objects
			Query query = session.createQuery("from Tag");
			Tag temp_tag;
			List <Tag>list = query.list();
			if(list==null || list.isEmpty())
				flag=true;
			Iterator<Tag> it=list.iterator();
			boolean exists=false;
			
			//checking if a tag which wasn't before was added
			while (it.hasNext()){

				temp_tag=it.next();
				if(temp_tag.getTag().equals(labels[i])){	 
					exists=true;
					break;
				}
				if(exists==false)
					flag=true;

			}

			//adding to data base
			manager.saveTag(tag);
			System.out.println("User saved with tag = "+tag.getTag());

			session.flush();
		}
		
		if(flag)//we need to update the GUI
		{
			
			try {
				if(socket ==null)
				{
					socket=new Socket("localhost",4444);
					out = new PrintWriter(socket.getOutputStream(),true);
				}

				//sending update to the tagSearchGUI program
				out.println("update");

			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				
			}
			
		}
		
	
	}

	/**
	 * 
	 * @param filePath
	 * deletes from database all Tag objects that relate to filePath
	 */
	public static void deleteFile(String filePath ){
		
		
		 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
		 HashMap<String, Integer> map = new HashMap<String, Integer>(); 
		 Session session = sessionFactory.openSession();
		 TagsManager manager = new TagsManager(session);
		 
		 //getting all tag objects
		 Query query = session.createQuery("from Tag");
		 Tag tag;
		 List <Tag>list = query.list();
		 Iterator<Tag> it=list.iterator();
		 boolean socket_update=false;

		//preparing map which includes for each file number of tags
		 while(it.hasNext()){
			 tag = it.next();
			 if(map.containsKey(tag.getTag()))
				 map.put(tag.getTag(), map.get(tag.getTag())+1);
			 else
				 map.put(tag.getTag(), 1);
		 }

		 it=list.iterator();
		 while (it.hasNext()){

			 tag=it.next();
			 //we found a line which relates to filePath
			 if(tag.getFilePath().equals(filePath)){	

				 //deleting from data base
				 manager.deleteTag(tag);
				 //need to update if we deleted the last tag and it's no longer in data base
				 if(map.get(tag.getTag()) == 1){
					 socket_update = true;
				 }
			 }
			

		 }
		 session.flush();

		 if(socket_update)//need to inform GUI that tag was deleted
		 {
			 try {
				 if(socket ==null)
				 {
					 socket=new Socket("localhost",4444);
					 out = new PrintWriter(socket.getOutputStream(),true);
				 }

				 out.println("upda666te");	 

			 } catch (UnknownHostException e) {
				 // TODO Auto-generated catch block
				
			 } catch (IOException e) {
				 // TODO Auto-generated catch block
			
			 }

		 }



			
	}
	

}


